package com.jy.api.service.impl;

import com.jy.api.dao.ProductDao;
import com.jy.api.dao.ProductSupplyTimeDao;
import com.jy.api.domain.Product;
import com.jy.api.domain.ProductSupplyTime;
import com.jy.api.service.ProductSupplyTimeService;
import com.jy.api.signUpReq.admin.ProductSupplyTimesSignUpReq;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by lihu on 2017/12/27.
 */
@Service
public class ProductSupplyTimeServiceImpl implements ProductSupplyTimeService {

    @Autowired
    ProductSupplyTimeDao productSupplyTimeDao;

    @Autowired
    ProductDao productDao;

    @Override
    public List<ProductSupplyTime> getStoreAll(String storeId) {

        return productSupplyTimeDao.findByStoreIdAndEnabled(storeId, true);
    }

    @Override
    @Transactional
    public void delete(String id) {
        ProductSupplyTime productSupplyTime = productSupplyTimeDao.findOne(id);
        if (productSupplyTime != null) {
            List<Product> products = productDao.findByStoreIdAndEnabledAndSupplyTimesIsNotNull(
                    productSupplyTime.getStoreId(), true);
            //商品修改时段
            for (Product product : products) {
                product.deleteSupplyTimes(id);
            }
            if (products.size() > 0) {
                productDao.save(products);
            }
            productSupplyTimeDao.delete(id);
        }
    }


    @Override
    @Transactional
    public void saveOrUpdateSupplyTime(ProductSupplyTimesSignUpReq signUpReq) {
        ProductSupplyTime productSupplyTime = new ProductSupplyTime();
        BeanUtils.copyProperties(signUpReq, productSupplyTime);
        List<Product> products = productDao.findByStoreIdAndEnabledAndSupplyTimesIsNotNull(
                productSupplyTime.getStoreId(), true);
        for (Product product : products) {
            product.updateSupplyTimes(productSupplyTime);
        }
        if (products.size() > 0) {
            productDao.save(products);
        }
        productSupplyTimeDao.save(productSupplyTime);
    }
}
